
// Map
	var map;
// LatLng	
	var currLocation;
	var lastSearchedLocation;
// Marker
	var selfMarker;
// Services
	var directionsDisplay;
	var directionsService;
	var geocoder;

// Waypoints list
	var currWaypoints = [];
	var waypoint_marker =[];
	
// Panel 
	var stepDisplay;
	
	function initialize(location) 
	{
	  	console.log(":: initialize" + location);
	     currLocation = new google.maps.LatLng(location.coords.latitude,location.coords.longitude);
		geocoder = new google.maps.Geocoder();
		var mapOptions = {
			zoom : 11, 
			center : new google.maps.LatLng(46.771, 23.596) 
		};
		map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
		
		directionsService = new google.maps.DirectionsService();
		directionsDisplay = new google.maps.DirectionsRenderer( {draggable: true} );
		
		directionsDisplay.setMap(map);
		
/* 	     currLocation = new google.maps.LatLng(currLocation.coords.latitude,currLocation.coords.longitude); */
		 selfMarker = new google.maps.Marker({
			 position:currLocation,
			 map: map,
			 title: 'current position',
			 draggable: true
		   });  
		

	}
	  google.maps.event.addDomListener(window, 'load', initialize);
	  
	  $(document).ready(function(){
		  console.log(":: (document).ready ");
		  navigator.geolocation.getCurrentPosition(initialize); 
		  
		/*   google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
			    watch_waypoints();
		  }); */
	  	  
		  $("#rrBtn").click(
				  function() {
					  console.log("::  $(#rrBtn).click");
					  map.setCenter(currLocation);
					  map.setZoom(18);
					  if (selfMarker === undefined) {
					  	console.log(":: Undefined selfMarker");
						  selfMarker = new google.maps.Marker({
								 position: currLocation,
								 map: map,
								 title: 'current position',
								 draggable: true
							   });
					} else {
					  	console.log(":: Defined selfMarker");
					  	selfMarker.setPosition(currLocation);

					}
					 
					  currLocation = map.getCenter();
					  console.log("> current location new setting :: " + currLocation);
				}
		  );
		  
		  $("#searchBtn").click(
				  function(){
					  console.log("::  $(#searchBtn).click");
					  // clean list from map
					 /*  console.log("list details: " + currWaypoints.length); */

					  var address = (document.getElementById('searchFld').value).toLowerCase();
					  var searchAttr =  address.concat(",Cluj-Napoca");
					  console.log("> search param :: " + searchAttr);
					  
					  // hide selfMarker -> new point by route for starting point
					  selfMarker.setVisible(false);
					  
					  geocoder.geocode( { 'address': searchAttr, 'componentRestrictions':{'country':'RO'}}, function(results, status) {
						  if (status == google.maps.GeocoderStatus.OK) {
							      map.setCenter(results[0].geometry.location);
							      calcRoute(results[0].geometry.location);
							      map.setZoom(15);
							      lastSearchedLocation = results[0].geometry.location;
					    } else {
					     	alert('> Geocode was not successful for the following reason: ' + status);
					    }
					  });
				  });
		  
		  
		  $("#saveRouteBtn").click(
				  function(){
					  console.log("::  $(#saveRouteBtn).click");
					  // clean list from map
				/* 	  console.log("list details: " + currWaypoints.length); */
			
					  var address = (document.getElementById('searchFld').value).toLowerCase();
					  var searchAttr =  address.concat(",Cluj-Napoca");
					  console.log("> search param :: " + searchAttr);
					  
					  // hide selfMarker -> new point by route for starting point
					  selfMarker.setVisible(false);
					  
					  geocoder.geocode( { 'address': searchAttr, 'componentRestrictions':{'country':'RO'}}, function(results, status) {
						  if (status == google.maps.GeocoderStatus.OK) {
							      map.setCenter(results[0].geometry.location);
							      currWaypoints = directionsDisplay.directions.routes[0].legs[0].via_waypoints;
							      calcRoute(results[0].geometry.location);
							      console.log("overview path: " + directionsDisplay.getDirections());
							      map.setZoom(15);
							      lastSearchedLocation = results[0].geometry.location;
                                  
                                 /*  console.log(currWaypoints.toString()); */
                                  
					    } else {
					     	alert('> Geocode was not successful for the following reason: ' + status);
					    }
					  });
				  });
		  
		  function calcRoute(dest) {
			  console.log("::  ::  CalcRoute() - REQ: " 
					 + " | origin:" + currLocation
				     + " | destination:" + dest
				     + " | waypoints:" + currWaypoints
				     + " | travelMode:" + google.maps.TravelMode.DRIVING
			  );

			 
			  directionsService.route(
					  {
					      origin: currLocation,
					      destination: dest,
					      waypoints: currWaypoints,
					      travelMode: google.maps.TravelMode.DRIVING
					  },
					  function(response, status) {
					    if (status == google.maps.DirectionsStatus.OK) 
					    {
					      directionsDisplay.setDirections(response);
					    }
					  }
				);
			}
		  
		  
		  // trash
		  function watch_waypoints() {
			  clear_markers();
			  var wpts = directionsDisplay.directions.routes[0].legs[0].via_waypoints;
			  for(var i=0; i<wpts.length; i++) {
			    var marker = new google.maps.Marker({
			        map: map,
			        //icon: "/images/blue_dot.png",
			        position: new google.maps.LatLng(wpts[i].lat(), wpts[i].lng()),
			        title: i.toString()
			        });
			    waypoint_markers.push(marker);
			    google.maps.event.addListener(marker, 'click', function() {
			        infowindow.setContent("double click to delete this waypoint");
			        infowindow.open(map, this);
			    });
			    google.maps.event.addListener(marker, 'dblclick', function() {
			        marker.setMap(null);
			        wpts.splice(parseInt(this.title), 1);
			        calcRoute(wpts);
			        directionsDisplay.setOptions({ preserveViewport: true, draggable: true});
			    });
			  }
			}
		  
		  function clear_markers() {
			  for(var i=0; i<waypoint_markers.length; i++){
			    waypoint_markers[i].setMap(null);
			  }
			}


	  });
